package com.distribute.application.api.rest.member;

import java.io.File;
import java.io.IOException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.stream.FileImageOutputStream;

import org.apache.commons.codec.binary.Base64;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.distribute.application.api.BaseApiController;
import com.distribute.application.api.utils.DateUtils;
import com.distribute.application.api.utils.EmojiStringUtils;
import com.distribute.application.api.utils.mobile.MobileCodeUtil;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.title;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.model.Account;
import com.distribute.framework.model.Configur;
import com.distribute.framework.model.Coupon;
import com.distribute.framework.model.HeedCoupon;
import com.distribute.framework.model.InvitCoupon;
import com.distribute.framework.model.InvitRecord;
import com.distribute.framework.model.Member;
import com.distribute.framework.model.NewGifts;
import com.distribute.framework.model.Region;
import com.distribute.framework.model.SrvOauth;
import com.distribute.framework.model.TbMsg;
import com.distribute.framework.model.TbPartners;
import com.distribute.framework.model.TbReturnCoupon;

@RestController(value="api.MemberAuthorController")
public class MemberAuthorController extends BaseApiController{
	@RequestMapping("/api/address/getAddressListByPid.do")
	public @title("根据父级ID获取城市列表信息") Protocol getAddressListByPid(
		@title("父级编号") Long pid
		/************API_PARAMS_LIST************/
		/************API_PARAMS_LIST************/
	){
		Protocol protocol = Protocol.create(true, null);
		List<Region> tAddresses=Region.where.parent(pid).list(1000);
		List<Map<String, Object>> citys=new ArrayList<Map<String, Object>>();
		for (Region region : tAddresses) {
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("id", region.getId());
			map.put("name", region.getName());
			map.put("have", 0);
			citys.add(map);
		}
		protocol.set("list", citys);
		return protocol;
	}
	/**
	 *  查看 那些街道已经有合伙人了
	 * @param pid
	 * @return
	 */
	@RequestMapping("/api/address/getAddressListByPidSub.do")
	public @title("查看 那些街道已经有合伙人了") Protocol getAddressListByPidSub(
		@title("父级编号") Long pid,
		@title("品牌") Long banrdId
		/************API_PARAMS_LIST************/
		/************API_PARAMS_LIST************/
	){
		Protocol protocol = Protocol.create(true, null);
		Region regiona=Region.where.id(pid).get();
		List<Region> tAddresses=Region.where.parent(pid).list(1000);
		List<Map<String, Object>> citys=new ArrayList<Map<String, Object>>();
		for (Region region : tAddresses) {
			if (regiona!=null&&regiona.getLevel()==(short)3) {
				TbPartners partners=TbPartners.where.tbpBrand(banrdId).tbpJiedao(region.getId()).get();
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("id", region.getId());
				map.put("name", region.getName());
				if (partners!=null) {
					map.put("have", 1);
				}else {
					map.put("have", 0);
				}
				citys.add(map);
			}else {
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("id", region.getId());
				map.put("name", region.getName());
				map.put("have", 0);
				citys.add(map);
			}
			
		}
		protocol.set("list", citys);
		return protocol;
	}
	@RequestMapping("/api/member/authPhones.do")
	public @title("后手机号码授权")  Protocol authPhones(
			@title("vi") String vi,
			@title("encData") String encData,
			@title("session_key") String session_key,
			@title("openid") String openid,
			@title("banrdId") String banrdId
	) throws Exception{
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.openid(openid).get();//根据openId查找用户
		if (member!=null) {//不是新用户就 修改手机号码
			 SrvOauth srvOauth = SrvOauth.where.soTicket(openid).get();
				if(srvOauth==null){
					srvOauth=new SrvOauth();
					srvOauth.setSoToken(Utils.md5(session_key));
					srvOauth.setSoTicket(openid);
					srvOauth.setSoParams(session_key);
					srvOauth.setSoUserId(member.getId());
					srvOauth.setSoApiClient(this.getClient());
					srvOauth.setSoUpdateTime(new Date());
					srvOauth.save();
				}else{
					srvOauth.setSoToken(Utils.md5(session_key));
					srvOauth.setSoTicket(openid);
					srvOauth.setSoParams(session_key);
					srvOauth.setSoUserId(member.getId());
					srvOauth.setSoApiClient(this.getClient());
					srvOauth.setSoUpdateTime(new Date());
					srvOauth.update();
				}
			String jsonObject = decrypt( Base64.decodeBase64(session_key),Base64.decodeBase64(vi),Base64.decodeBase64(encData));
			JSONObject jObject=JSON.parseObject(jsonObject);
			member.setMobile(jObject.getString("phoneNumber"));
			member.update();
			if (banrdId!=null) {
			Coupon coupon=Coupon.where.sources((short)2).member(member.getId()).merchant(Long.parseLong(banrdId)).get();
			if (coupon==null) {
				NewGifts newGifts=NewGifts.where.merchant(Long.parseLong(banrdId)).get();
				if (newGifts!=null) {
					Coupon coupon4=new Coupon(//邀请人添加邀请优惠券
							newGifts.getDiscount()//折扣 [非空]
						 	,Long.parseLong(banrdId)//所属品牌 [非空]
						 	,newGifts.getCommodity()//适用产品 [非空]
						 	,member.getUid()//用户 [非空]
						 	,(short)0
						 	,newGifts.getExpiryDate()//有效期[非空]
						 	,(short)2
						 	,newGifts.getId()
						 	,(short)1
						 	,new Date()//修改时间 [非空]
						 	,new Date()//添加时间 [非空]
						 	,(short)1//状态 [非空]
							);
		       		coupon4.save();
					TbMsg msg4=new TbMsg(//给邀请人一条消息
							member.getUid()//会员
							 	,"您获得一张"+newGifts.getDiscount()+"新人大礼优惠券"//内容
							 	,new Date()//时间
								);
					msg4.save();
				}
			}
			}
			protocol.set("ko", "1");
			protocol.set("pingtai", Configur.where.get().toJSON());
			protocol.set("userInfo", member.toJSON());
			protocol.set("session_key", srvOauth.getSoParams());
			protocol.set("openid", srvOauth.getSoTicket());
			protocol.set("token", srvOauth.getSoToken());
		}
		return protocol;
	}
	 public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
	        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
	        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
	        //解析解密后的字符串
	        return new String(cipher.doFinal(encData),"UTF-8");
	    }
	@RequestMapping("/api/upload/uploadimage.do")
	public @title("小程序图片上传接口")  Protocol uploadimage(
			@title("文件名") String name,
			@title("文件") MultipartFile file
	) throws IOException {
		 String upload_forder = Utils.config("upload.forder");//上传图片保存的路径
		 String upload_domain = Utils.config("upload.domain");//图片服务的域名地址	
		Protocol protocol = Protocol.create(true, null);
		if (!file.isEmpty()) {
			if (name.indexOf('.') == -1) {
				
				protocol.set("msg", "文件名称错误");
				protocol.set("type", 2);
				return protocol;
			}
			 String postfix = name.split("\\.")[name.split("\\.").length - 1];
			String sApp="qrcode";//上传应用
			String filePah=sApp+"/";
			new File(upload_forder+filePah).mkdirs();
			String fileName="dpImg"+new Date().getTime()+"."+postfix;
			byte2image(file.getBytes(),upload_forder+filePah+fileName);
			 protocol.set("msg", "上传成功");
			 protocol.set("url", upload_domain+filePah+fileName);
				protocol.set("type", 1);
				return protocol;
        } else {
        	protocol.set("msg", "文件不能为空");
			protocol.set("type", 2);
			return protocol;
        }
	}
	public static void byte2image(byte[] data, String path) {
        if (data.length < 3 || path.equals(""))
            return;
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            System.out.println("Make Picture success,Please find image in " + path);
        }
        catch (Exception ex) {
            System.out.println("Exception: " + ex);
            ex.printStackTrace();
        }
    }
	/**
	 * 获取手机验证码
	 * @param mobile
	 * @return
	 */
	@RequestMapping("/api/member/getCodes.do")
	public @title("获取手机验证码")  Protocol getCodes(
			@title("手机号") String mobile
	){
        Protocol protocol = Protocol.create(true, null);
		String captcha = MobileCodeUtil.genCaptcha(mobile);
	    MobileCodeUtil.sendTextMessage(mobile, captcha);
	    protocol.set("code", captcha);
		return protocol;
	}
	/**
	 * 检测验证码是否正确
	 * @param mobile
	 * @return
	 */
	@RequestMapping("/api/member/isTrueCodes.do")
	public @title("检测验证码是否正确")  Protocol isTrueCodes(
			@title("手机号") String mobile,
			@title("验证码") String code
	){
        Protocol protocol = Protocol.create(true, null);
        if (!MobileCodeUtil.validateCaptcha(mobile, code)) {
			protocol.setMessage("验证码有误");
			protocol.set("type", 2);
			protocol.setSuccess(false);
			return protocol;
		}else {
			protocol.set("type", 1);
			return protocol;
		}
	}
	/**
	 * 获取sessionKey
	 * @param jscode wx.login获取的code
	 * @return
	 */
	@RequestMapping("/api/member/getSessionKey.do")
	public @title("获取sessionKey")  Protocol getSessionKey(
			@title("wx.login()获取的code") String jscode,
			@title("红包ID") Long redId
			
	){
		Protocol protocol = Protocol.create(true, null);
		Map json = new HashMap();
		try {
			json = (Map) JSON.parse(Utils.doPost("https://api.weixin.qq.com/sns/jscode2session?appid="+Utils.config("wx.mp1.appid")+"&secret="+Utils.config("wx.mp1.secret")+"&js_code="+jscode+"&grant_type=authorization_code",""));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String openid = (String) json.get("openid");
		String session_key = (String) json.get("session_key");
		if(Utils.empty(openid)||Utils.empty(session_key)){
			return Protocol.create(false, "调用微信服务接口时出错","jscode_session_error").set("result", json);
		}
		protocol.set("openid", openid);
		protocol.set("session_key", session_key);
		return protocol;
	}
	/**
	 * 用户授权基本信息
	 * @param jscode wx.login获取的code
	 * @return
	 */
	@RequestMapping("/api/member/registerUser.do")
	public @title("用户授权基本信息")  Protocol registerUser(
			@title("wx.login()获取的code") String jscode,
			@title("昵称") String nickname,
			@title("性别") Short sex,//性别
			@title("头像") String header
	){
		Protocol protocol = Protocol.create(true, null);
		Map json = new HashMap();
		try {
			json = (Map) JSON.parse(Utils.doPost("https://api.weixin.qq.com/sns/jscode2session?appid="+Utils.config("wx.mp1.appid")+"&secret="+Utils.config("wx.mp1.secret")+"&js_code="+jscode+"&grant_type=authorization_code",""));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String openid = (String) json.get("openid");
		String session_key = (String) json.get("session_key");
		if(Utils.empty(openid)||Utils.empty(session_key)){
			return Protocol.create(false, "调用微信服务接口时出错","jscode_session_error").set("result", json);
		}
		Member member=Member.where.openid(openid).get();
		member.setHeader(header);
		member.setSex(sex);
		member.setNickName(EmojiStringUtils.replaceEmoji(nickname));
		member.setAuthStatus((short)1);
		member.setStatus((short)1);
		member.update();
		/*********根据openID获取用户 **********/
		SrvOauth srvOauth = SrvOauth.where.soTicket(openid).get();
		if(srvOauth==null){
			srvOauth=new SrvOauth();
			srvOauth.setSoToken(Utils.md5(session_key));
			srvOauth.setSoTicket(openid);
			srvOauth.setSoParams(session_key);
			srvOauth.setSoUserId(member.getId());
			srvOauth.setSoApiClient(this.getClient());
			srvOauth.setSoUpdateTime(new Date());
			srvOauth.save();
		}else{
			srvOauth.setSoToken(Utils.md5(session_key));
			srvOauth.setSoTicket(openid);
			srvOauth.setSoParams(session_key);
			srvOauth.setSoUserId(member.getId());
			srvOauth.setSoApiClient(this.getClient());
			srvOauth.setSoUpdateTime(new Date());
			srvOauth.update();
		}
		protocol.set("msg", "已登录");
		protocol.set("type", 1);
		protocol.set("pingtai", Configur.where.get().toJSON());
		protocol.set("userInfo", member.toJSON());
		protocol.set("session_key", srvOauth.getSoParams());
		protocol.set("openid", srvOauth.getSoTicket());
		return protocol.set("token", srvOauth.getSoToken());
	}
	/**
	 * 检测是否登录
	 * @param jscode wx.login获取的code
	 * @return
	 */
	@RequestMapping("/api/member/isLogin.do")
	public synchronized @title("检测是否登录")  Protocol isLogin(
			@title("wx.login()获取的code") String jscode,
			@title("推荐人") Long otherId,
			@title("关注有礼参数") String gzflag,
			@title("品牌编号") Long banrdId
	){
		Protocol protocol = Protocol.create(true, null);
		if (gzflag!=null&&!gzflag.equals("")) {
			HeedCoupon gzylpingtai=HeedCoupon.where.accessCode("/pages/member/tab3/coupon/gzcoupon?pmarms="+gzflag).get();
			if (gzylpingtai!=null) {
				protocol.set("gzs", gzylpingtai.toJSON());
			}else {
				protocol.set("gzs", null);
			}
			
		}
		Map json = new HashMap();
		try {
			json = (Map) JSON.parse(Utils.doPost("https://api.weixin.qq.com/sns/jscode2session?appid="+Utils.config("wx.mp1.appid")+"&secret="+Utils.config("wx.mp1.secret")+"&js_code="+jscode+"&grant_type=authorization_code",""));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String openid = (String) json.get("openid");
		String session_key = (String) json.get("session_key");
		if(Utils.empty(openid)||Utils.empty(session_key)||openid==null){
			return Protocol.create(false, "调用微信服务接口时出错","jscode_session_error").set("result", json);
		}
		/*********根据openID获取用户 **********/
		Member member = Member.where.openid(openid).get();
		/*********根据openID获取用户 **********/
	
		if (member==null) {
			Member member2=new Member();
			member2.setAuthStatus((short)0);
			member2.setOpenid(openid);
			member2.setAddTime(new Date());
			member2.setStatus((short)1);
			member2.save();
			Member member3 = Member.where.openid(openid).get();
			
			Account account=new Account(
					member3.getId()//所属会员 [非空]
					,""
					,""
					,""
					,""
				 	,0.0//余额 [非空]
				 	,0.0
				 	,0.0
				 	,new Date()//修改时间 [非空]
				 	,new Date()//添加时间 [非空]
				 	,(short)1//状态 [非空]
					);
			account.save();
			SrvOauth srvOauth = SrvOauth.where.soTicket(openid).get();
			if(srvOauth==null){
				srvOauth=new SrvOauth();
				srvOauth.setSoToken(Utils.md5(session_key));
				srvOauth.setSoTicket(openid);
				srvOauth.setSoParams(session_key);
				srvOauth.setSoUserId(member3.getId());
				srvOauth.setSoApiClient((long)1);
				srvOauth.setSoUpdateTime(new Date());
				srvOauth.save();
			}else{
				srvOauth.setSoToken(Utils.md5(session_key));
				srvOauth.setSoTicket(openid);
				srvOauth.setSoParams(session_key);
				srvOauth.setSoUserId(member3.getId());
				srvOauth.setSoApiClient((long)1);
				srvOauth.setSoUpdateTime(new Date());
				srvOauth.update();
			}
			if (otherId!=null) {
				Member member4 = Member.where.uid(otherId).get();
				TbMsg msg=new TbMsg(
						otherId//会员
						 	,"您增加了一位粉丝"//内容
						 	,new Date()//时间
							);
					msg.save();
				member3.settTop(member4.getUid$());//直接上级
				member3.setmTop(member4.getNickName());
				if (member4.gettTop()!=null&&!member4.equals("")) {
					Member mTopto=Member.where.uid(Long.valueOf(member4.gettTop())).get();
					if (mTopto!=null) {
						member3.settToptop(mTopto.getUid$());
						member3.setmToptop(mTopto.getNickName());
					}
				}
				member3.update();
				if (member4!=null) {
					InvitRecord invitRecorda=InvitRecord.where.invitedPerson(member3.getId()).recom(otherId).get();
					if (invitRecorda==null) {
						InvitRecord invitRecord=new InvitRecord();
						invitRecord.setInvitedPerson(member3.getId());
						invitRecord.setRecom(member4.getId());
						invitRecord.setInvitrType((short)1);
						invitRecord.setUpdateTime(new Date());
						invitRecord.setAddTime(new Date());
						invitRecord.setStatus((short)1);
						InvitCoupon invitCoupon=InvitCoupon.where.merchant(banrdId).get();//邀请赠送优惠卷
						if (invitCoupon!=null) {
						invitRecord.setInvitedDiscount(NewGifts.where.get().getDiscount());
						invitRecord.setInvitedCoupon(invitCoupon.getId());
						invitRecord.setRecomDiscount(invitCoupon.getRecomDiscount());
						invitRecord.setRecomCoupon(invitCoupon.getId());
						Coupon coupon=new Coupon(//邀请人
							 	invitCoupon.getRecomDiscount()//折扣 [非空]
							 	,invitCoupon.getMerchant()//所属品牌 [非空]
							 	,invitCoupon.getCommodity()//适用产品 [非空]
							 	,otherId//用户 [非空]
							 	,(short)0
							 	,invitCoupon.getExpiryDate()//有效期[非空]
							 	,(short)3
							 	,invitCoupon.getId()
							 	,(short)1
							 	,new Date()//修改时间 [非空]
							 	,new Date()//添加时间 [非空]
							 	,(short)1//状态 [非空]
								);
						coupon.save();
						TbMsg msg2=new TbMsg(
								otherId//会员
								 	,"您获得一张"+invitCoupon.getRecomDiscount()+"折邀请优优惠券"//内容
								 	,new Date()//时间
									);
		           		msg2.save();
//						Coupon coupon2=new Coupon(//被邀请人
//							 	invitCoupon.getNewDiscount()//折扣 [非空]
//							 	,invitCoupon.getMerchant()//所属品牌 [非空]
//							 	,invitCoupon.getCommodity()//适用产品 [非空]
//							 	,member3.getId()//用户 [非空]
//							 	,(short)0
//							 	,invitCoupon.getExpiryDate()//有效期[非空]
//							 	,(short)3
//							 	,invitCoupon.getId()
//							 	,(short)1
//							 	,new Date()//修改时间 [非空]
//							 	,new Date()//添加时间 [非空]
//							 	,(short)1//状态 [非空]
//								);
//						coupon2.save();
//						TbMsg msg3=new TbMsg(
//								member3.getId()//会员
//								 	,"您获得一张"+invitCoupon.getNewDiscount()+"新人折扣优惠券"//内容
//								 	,new Date()//时间
//									);
//		           		msg3.save();
					}
						invitRecord.save();
					}
					}
					
			}
			if(banrdId!=null){
				NewGifts newGifts=NewGifts.where.merchant(banrdId).putIn((short)2).get();
				if (newGifts!=null) {
					if (newGifts.getExpiryDate().getTime()>new Date().getTime()) {
						Coupon coupon=Coupon.where.sources((short)2).member(member3.getId()).merchant(banrdId).get();
						if (coupon==null) {
							protocol.set("getnew", true);
							protocol.set("coupon",  newGifts.toJSON());
						}
					}
				}
			}
			protocol.set("session_key", session_key);
			protocol.set("openid", openid);
		    protocol.set("token", srvOauth.getSoToken());
		    protocol.set("userInfo", member3.toJSON());
		    protocol.set("pingtai", Configur.where.get().toJSON());
			protocol.set("type", 2);
			return protocol.set("msg", "新用户");
		}else {
			if (otherId!=null) {
				if (banrdId!=null) {
				InvitCoupon invitCoupona=InvitCoupon.where.merchant(banrdId).get();//邀请赠送优惠卷
				Long otherCount=InvitRecord.where.recom(otherId).invitrType((short)2).addTimeStart(DateUtils.getDateBeforeZroe(new Date(), invitCoupona.getInvitcCycle())).addTimeEnd(new Date()).count();
				if (otherCount==0) {
					InvitRecord invitRecord=new InvitRecord();
					invitRecord.setInvitedPerson(member.getId());
					invitRecord.setRecom(otherId);
					invitRecord.setUpdateTime(new Date());
					invitRecord.setAddTime(new Date());
					invitRecord.setStatus((short)1);
					invitRecord.setInvitrType((short)2);
					invitRecord.setInvitedDiscount(NewGifts.where.get().getDiscount());
					invitRecord.setInvitedCoupon(invitCoupona.getId());
					invitRecord.setRecomDiscount(invitCoupona.getRecomDiscount());
					invitRecord.setRecomCoupon(invitCoupona.getId());
					invitRecord.save();
					Coupon coupon=new Coupon(//邀请人
							invitCoupona.getRecomDiscount()//折扣 [非空]
						 	,invitCoupona.getMerchant()//所属品牌 [非空]
						 	,invitCoupona.getCommodity()//适用产品 [非空]
						 	,otherId//用户 [非空]
						 	,(short)0
						 	,invitCoupona.getExpiryDate()//有效期[非空]
						 	,(short)3
						 	,invitCoupona.getId()
						 	,(short)1
						 	,new Date()//修改时间 [非空]
						 	,new Date()//添加时间 [非空]
						 	,(short)1//状态 [非空]
							);
					coupon.save();
					TbMsg msg2=new TbMsg(
							otherId//会员
							 	,"您获得一张"+invitCoupona.getRecomDiscount()+"折新人邀请优优惠券"//内容
							 	,new Date()//时间
								);
	           		msg2.save();
				}
				
				}
				
				if (banrdId!=null) {
					InvitCoupon invitCoupon=InvitCoupon.where.merchant(banrdId).get();//邀请赠送优惠卷
					if (invitCoupon!=null) {
						System.out.println("invitCoupon---"+invitCoupon.toJSON(true));
					   int days = DateUtils.towDateDays(member.getAddTime(),new Date());
						System.out.println("天数---"+days);
						System.out.println("周期---"+invitCoupon.getInvitcCycle());
					    if (days>invitCoupon.getInvitcCycle()) {
					    	Long countsLong=TbReturnCoupon.where.tbrcMember(member.getUid()).tbrcYq(otherId).tbrcAddTimeStart(DateUtils.getDateBeforeZroe(new Date(), invitCoupon.getInvitcCycle())).tbrcAddTimeEnd(new Date()).count();
							System.out.println("数量---"+countsLong);
							if (countsLong>0) {
							}else {
								System.out.println("头像---"+member.getHeader());
					           		Coupon coupon4=new Coupon(//邀请人添加邀请优惠券
										 	invitCoupon.getInvitcOldDiscount()//折扣 [非空]
										 	,invitCoupon.getMerchant()//所属品牌 [非空]
										 	,invitCoupon.getCommodity()//适用产品 [非空]
										 	,member.getUid()//用户 [非空]
										 	,(short)0
										 	,invitCoupon.getExpiryDate()//有效期[非空]
										 	,(short)6
										 	,invitCoupon.getId()
										 	,(short)1
										 	,new Date()//修改时间 [非空]
										 	,new Date()//添加时间 [非空]
										 	,(short)1//状态 [非空]
											);
					           		coupon4.save();
									TbMsg msg4=new TbMsg(//给邀请人一条消息
											otherId//会员
											 	,"您获得一张"+invitCoupon.getInvitcOldDiscount()+"老客户回归优惠券"//内容
											 	,new Date()//时间
												);
									msg4.save();
									TbReturnCoupon returnCoupon=new TbReturnCoupon(//给回归用户一条可领取优惠券
										 	member.getUid()//会员
										 	,otherId//邀请人
										 	,banrdId//品牌
										 	,invitCoupon.getId()//优惠券
										 	,(short)2//领取情况
										 	,new Date()//添加时间
										 );
									returnCoupon=returnCoupon.save();
							  }
						}
					}
				}
			}
		}
		if(banrdId!=null){
			NewGifts newGifts=NewGifts.where.merchant(banrdId).get();
			Coupon coupon=Coupon.where.sources((short)2).member(member.getId()).merchant(banrdId).get();
			if (newGifts!=null&&coupon!=null) {
				if (coupon==null) {
					protocol.set("getnew", true);
					protocol.set("coupon", newGifts.toJSON());
				}
			}
//			InvitCoupon invitCoupon=InvitCoupon.where.merchant(banrdId).get();//邀请赠送优惠卷
//			List<TbReturnCoupon> returnCoupons=TbReturnCoupon.where.tbrcMember(member.getUid()).tbrcBrand(banrdId).tbrcGet((short)1).list(10);
//			if(invitCoupon!=null&&returnCoupons.size()>0) {
//					protocol.set("returnCoupon", true);
//					protocol.set("rcoupon", invitCoupon.toJSON());
//			}else {
//				protocol.set("returnCoupon", false);
//				protocol.set("rcoupon", null);
//			}
		}
		List<InvitRecord> inList=InvitRecord.where.invitedPerson(member.getId()).list(2);
		if (otherId!=null&&inList.size()<1) {
			InvitRecord invitRecord=new InvitRecord();
			invitRecord.setInvitedPerson(member.getId());
			invitRecord.setRecom(otherId);
			invitRecord.setUpdateTime(new Date());
			invitRecord.setAddTime(new Date());
			invitRecord.setStatus((short)1);
			invitRecord.save();
		}
      
       SrvOauth srvOauth = SrvOauth.where.soTicket(openid).get();
		if(srvOauth==null){
			srvOauth=new SrvOauth();
			srvOauth.setSoToken(Utils.md5(session_key));
			srvOauth.setSoTicket(openid);
			srvOauth.setSoParams(session_key);
			srvOauth.setSoUserId(member.getId());
			srvOauth.setSoApiClient(this.getClient());
			srvOauth.setSoUpdateTime(new Date());
			srvOauth.save();
		}else{
			srvOauth.setSoToken(Utils.md5(session_key));
			srvOauth.setSoTicket(openid);
			srvOauth.setSoParams(session_key);
			srvOauth.setSoUserId(member.getId());
			srvOauth.setSoApiClient(this.getClient());
			srvOauth.setSoUpdateTime(new Date());
			srvOauth.update();
		}
		 if(member.getAuthStatus()==(short)0){//未授权
				protocol.set("type", 2);
				protocol.set("msg", "新用户");
				protocol.set("pingtai", Configur.where.get().toJSON());
				protocol.set("userInfo", member.toJSON());
				protocol.set("session_key", session_key);
				protocol.set("openid", srvOauth.getSoTicket());
				return protocol.set("token", srvOauth.getSoToken());
			}
		protocol.set("msg", "已登录");
		protocol.set("type", 1);
		protocol.set("pingtai", Configur.where.get().toJSON());
		protocol.set("userInfo", member.toJSON());
		protocol.set("session_key", session_key);
		protocol.set("openid", srvOauth.getSoTicket());
		return protocol.set("token", srvOauth.getSoToken());
	}
}
